<template>
  <div class="game-container">
    <div class="game-wrapper">
      <div class="left-panel">
        <div class="score-board">
          <div v-if="currentUser" class="user-info">
            <span class="welcome-text">欢迎, {{ currentUser }}</span>
            <button @click="handleLogout" class="logout-btn">登出</button>
          </div>
          <h2 class="current-score">当前分数：{{ score }}</h2>
          <button @click="startGame" v-if="!isPlaying" class="start-btn">
            {{ score > 0 ? '重新开始' : '开始游戏' }}
          </button>
        </div>
        <canvas ref="gameCanvas" width="400" height="400" class="game-canvas"></canvas>
      </div>
      
      <div class="right-panel">
        <div class="high-scores">
          <h3 class="leaderboard-title">🏆 排行榜</h3>
          <div class="score-list">
            <div v-for="(score, index) in highScores" :key="score.id" 
                 class="score-item" :class="{'top-three': index < 3}">
              <span class="rank">{{ index + 1 }}</span>
              <span class="player-name">{{ score.playerName }}</span>
              <span class="score-value">{{ score.score }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 登录对话框 -->
    <div v-if="showLoginDialog" class="login-dialog">
      <div class="login-content">
        <h3 class="auth-title">{{ isRegistering ? '注册新账号' : '登录' }}</h3>
        <input v-model="loginForm.username" placeholder="用户名" class="auth-input" />
        <input v-model="loginForm.password" type="password" placeholder="密码" class="auth-input" />
        <button @click="handleLogin" v-if="!isRegistering" class="auth-btn login">登录</button>
        <button @click="handleRegister" v-if="isRegistering" class="auth-btn register">注册</button>
        <button @click="toggleRegister" class="auth-btn toggle">
          {{ isRegistering ? '返回登录' : '没有账号？去注册' }}
        </button>
        <button @click="showLoginDialog = false" class="auth-btn cancel">取消</button>
      </div>
    </div>
  </div>
</template>

<script>
import request, { setAuthCredentials, checkAuthStatus, clearAuthCredentials } from '@/utils/request'

export default {
  name: 'SnakeGame',
  data() {
    return {
      canvas: null,
      ctx: null,
      snake: [],
      food: { x: 0, y: 0 },
      direction: { x: 0, y: 0 },
      score: 0,
      gameLoop: null,
      isPlaying: false,
      gridSize: 20,
      highScores: [],
      showLoginDialog: false,
      loginForm: {
        username: '',
        password: ''
      },
      currentUser: null,
      isRegistering: false
    }
  },
  mounted() {
    this.canvas = this.$refs.gameCanvas;
    this.ctx = this.canvas.getContext('2d');
    this.loadHighScores();
    window.addEventListener('keydown', this.handleKeyPress);
    this.checkInitialAuth();
  },
  methods: {
    startGame() {
      this.snake = [{ x: 10, y: 10 }];
      this.generateFood();
      this.score = 0;
      this.direction = { x: 0, y: 0 };
      this.isPlaying = true;
      this.gameLoop = setInterval(this.gameUpdate, 100);
    },
    
    gameUpdate() {
      this.moveSnake();
      this.checkCollision();
      this.draw();
    },
    
    moveSnake() {
      const head = { 
        x: this.snake[0].x + this.direction.x,
        y: this.snake[0].y + this.direction.y
      };
      
      this.snake.unshift(head);
      
      if (head.x === this.food.x && head.y === this.food.y) {
        this.score += 10;
        this.generateFood();
      } else {
        this.snake.pop();
      }
    },
    
    draw() {
      this.ctx.fillStyle = 'white';
      this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
      
      // 画蛇
      this.ctx.fillStyle = 'green';
      this.snake.forEach(segment => {
        this.ctx.fillRect(
          segment.x * this.gridSize,
          segment.y * this.gridSize,
          this.gridSize - 2,
          this.gridSize - 2
        );
      });
      
      // 画食物
      this.ctx.fillStyle = 'red';
      this.ctx.fillRect(
        this.food.x * this.gridSize,
        this.food.y * this.gridSize,
        this.gridSize - 2,
        this.gridSize - 2
      );
    },
    
    generateFood() {
      const maxPos = this.canvas.width / this.gridSize;
      this.food = {
        x: Math.floor(Math.random() * maxPos),
        y: Math.floor(Math.random() * maxPos)
      };
    },
    
    handleKeyPress(event) {
      switch(event.key) {
        case 'ArrowUp':
          if (this.direction.y !== 1) {
            this.direction = { x: 0, y: -1 };
          }
          break;
        case 'ArrowDown':
          if (this.direction.y !== -1) {
            this.direction = { x: 0, y: 1 };
          }
          break;
        case 'ArrowLeft':
          if (this.direction.x !== 1) {
            this.direction = { x: -1, y: 0 };
          }
          break;
        case 'ArrowRight':
          if (this.direction.x !== -1) {
            this.direction = { x: 1, y: 0 };
          }
          break;
      }
    },
    
    checkCollision() {
      const head = this.snake[0];
      const maxPos = this.canvas.width / this.gridSize;
      
      if (head.x < 0 || head.x >= maxPos || head.y < 0 || head.y >= maxPos) {
        this.gameOver();
      }
      
      for (let i = 1; i < this.snake.length; i++) {
        if (head.x === this.snake[i].x && head.y === this.snake[i].y) {
          this.gameOver();
        }
      }
    },
    
    async gameOver() {
      clearInterval(this.gameLoop);
      this.isPlaying = false;
      
      if (this.currentUser) {  // 如果已经有用户登录
        await this.saveScore(this.currentUser);
        await this.loadHighScores();
      } else {
        const isAuthenticated = await checkAuthStatus();
        if (!isAuthenticated) {
          this.showLoginDialog = true;
        } else {
          const response = await request.get('/auth/status');
          this.currentUser = response.data.username;
          await this.saveScore(this.currentUser);
          await this.loadHighScores();
        }
      }
    },
    
    async saveScore(playerName) {
      try {
        await request.post('/game/score', {
          playerName,
          score: this.score
        });
        await this.loadHighScores();  // 保存成功后刷新排行榜
      } catch (error) {
        console.error('保存分数失败:', error);
        if (error.response?.status === 401) {  // 如果是认证失败
          this.showLoginDialog = true;  // 显示登录框
        }
      }
    },
    
    async loadHighScores() {
      try {
        const timestamp = new Date().getTime();
        const response = await request.get(`/game/highscores?t=${timestamp}`);
        this.highScores = response.data;
      } catch (error) {
        console.error('加载排行榜失败:', error);
      }
    },
    
    async handleLogin() {
      try {
        const response = await request.post('/auth/login', {
          username: this.loginForm.username,
          password: this.loginForm.password
        });
        
        if (response.data.username) {
          this.showLoginDialog = false;
          this.currentUser = response.data.username;
          setAuthCredentials(this.loginForm.username, this.loginForm.password);
          await this.saveScore(this.loginForm.username);
          await this.loadHighScores();
        } else {
          alert(response.data.message || '登录失败');
        }
      } catch (error) {
        console.error('登录失败:', error);
        alert(error.response?.data?.message || '登录失败');
      }
    },
    
    async checkInitialAuth() {
      const isAuthenticated = await checkAuthStatus();
      if (isAuthenticated) {
        const response = await request.get('/auth/status');
        this.currentUser = response.data.username;
        // 不要重新设置认证信息，因为已经从 localStorage 恢复了
      }
    },
    
    async handleLogout() {
      clearAuthCredentials();
      this.currentUser = null;
    },
    
    toggleRegister() {
      this.isRegistering = !this.isRegistering;
      this.loginForm.username = '';
      this.loginForm.password = '';
    },
    
    async handleRegister() {
      try {
        const response = await request.post('/api/auth/register', {
          username: this.loginForm.username,
          password: this.loginForm.password
        });
        
        if (response.data === "注册成功") {
          alert('注册成功，请登录');
          this.isRegistering = false;
        } else {
          alert('注册失败：' + response.data);
        }
      } catch (error) {
        console.error('注册失败:', error);
        alert('注册失败');
      }
    }
  },
  beforeUnmount() {
    window.removeEventListener('keydown', this.handleKeyPress);
    clearInterval(this.gameLoop);
  }
}
</script>

<style scoped>
.game-container {
  min-height: 100vh;
  background: #f0f2f5;
  padding: 20px;
  font-family: 'Arial', sans-serif;
}

.game-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  display: flex;
  gap: 30px;
  justify-content: center;
  align-items: flex-start;
}

.left-panel {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.right-panel {
  background: white;
  padding: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  min-width: 300px;
}

.game-canvas {
  border: 2px solid #e8e8e8;
  border-radius: 8px;
  margin: 20px 0;
}

.score-board {
  text-align: center;
}

.current-score {
  font-size: 24px;
  color: #333;
  margin: 10px 0;
}

.start-btn {
  background: #4CAF50;
  color: white;
  border: none;
  padding: 12px 24px;
  border-radius: 6px;
  font-size: 18px;
  cursor: pointer;
  transition: background 0.3s;
}

.start-btn:hover {
  background: #45a049;
}

.user-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  margin-bottom: 15px;
}

.welcome-text {
  font-size: 16px;
  color: #666;
}

.logout-btn {
  padding: 6px 12px;
  font-size: 14px;
  background-color: #ff4444;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.logout-btn:hover {
  background-color: #ff3333;
}

.leaderboard-title {
  font-size: 22px;
  color: #333;
  margin-bottom: 20px;
  text-align: center;
}

.score-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.score-item {
  display: flex;
  align-items: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
  transition: transform 0.2s;
}

.score-item:hover {
  transform: translateX(5px);
}

.top-three {
  background: linear-gradient(45deg, #ffd700, #fff8e7);
}

.rank {
  font-weight: bold;
  width: 30px;
  color: #666;
}

.player-name {
  flex: 1;
  margin: 0 10px;
  color: #333;
}

.score-value {
  font-weight: bold;
  color: #4CAF50;
}

/* 登录对话框样式 */
.login-dialog {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  backdrop-filter: blur(5px);
}

.login-content {
  background: white;
  padding: 30px;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  gap: 15px;
  min-width: 300px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.auth-title {
  font-size: 24px;
  color: #333;
  text-align: center;
  margin-bottom: 10px;
}

.auth-input {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 16px;
  transition: border-color 0.3s;
}

.auth-input:focus {
  border-color: #4CAF50;
  outline: none;
}

.auth-btn {
  padding: 12px;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.auth-btn.login {
  background: #4CAF50;
  color: white;
}

.auth-btn.register {
  background: #2196F3;
  color: white;
}

.auth-btn.toggle {
  background: #f0f2f5;
  color: #666;
}

.auth-btn.cancel {
  background: #ff4444;
  color: white;
}

.auth-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

@media (max-width: 768px) {
  .game-wrapper {
    flex-direction: column;
    align-items: center;
  }
  
  .right-panel {
    width: 100%;
  }
}
</style> 